package com.unknowpupil.oauth2.config.auth;

import com.unknowpupil.oauth2.domain.TbPermission;
import com.unknowpupil.oauth2.domain.TbUser;
import com.unknowpupil.oauth2.service.ITbPermissionService;
import com.unknowpupil.oauth2.service.ITbUserService;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Classname: UserDetailsServiceImpl
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2019/12/18 19:43
 * @Description:
 * @Version: 1.0
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private ITbUserService userService;
    @Autowired
    private ITbPermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        TbUser user = userService.getByUsername(s);
        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
        if (user != null) {
            //认证授权，所有需要这个用户的权限
            List<TbPermission> tbPermissions = permissionService.selectByUserId(user.getId());
            tbPermissions.forEach(tbPermission -> {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(tbPermission.getEnname());
                grantedAuthorities.add(grantedAuthority);
            });
        }
        return new User(user.getUsername(),user.getPassword(),grantedAuthorities);
    }
}
